<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据加载和分页
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: '',
  status: ''
})

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加用户')
const formRef = ref(null)
const formData = reactive({
  id: '',
  username: '',
  nickname: '',
  email: '',
  mobile: '',
  sex: '',
  status: '1',
  roleIds: [],
  deptId: '',
  remark: ''
})
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 角色列表
const roleOptions = ref([
  { id: '1', name: '管理员' },
  { id: '2', name: '普通用户' },
  { id: '3', name: '访客' }
])

// 部门列表
const deptOptions = ref([
  { id: '1', name: '总公司' },
  { id: '2', name: '研发部' },
  { id: '3', name: '市场部' },
  { id: '4', name: '财务部' },
  { id: '5', name: '人事部' }
])

// 获取数据
const getList = () => {
  loading.value = true
  
  // 模拟请求后端API
  setTimeout(() => {
    // 模拟数据
    const mockData = []
    for (let i = 0; i < queryParams.pageSize; i++) {
      const index = (queryParams.pageNum - 1) * queryParams.pageSize + i + 1
      mockData.push({
        id: index.toString(),
        username: `user${index}`,
        nickname: `用户${index}`,
        email: `user${index}@example.com`,
        mobile: `1385555${String(index).padStart(4, '0')}`,
        sex: index % 3 === 0 ? '2' : (index % 2 === 0 ? '1' : '0'),
        status: index % 5 === 0 ? '0' : '1',
        createdTime: new Date().toLocaleString(),
        roleIds: [index % 3 === 0 ? '3' : (index % 2 === 0 ? '2' : '1')],
        deptId: index % 5 + 1 + '',
        remark: `备注信息${index}`
      })
    }
    
    // 过滤
    let filteredData = [...mockData]
    if (queryParams.username) {
      filteredData = filteredData.filter(item => item.username.includes(queryParams.username))
    }
    if (queryParams.status) {
      filteredData = filteredData.filter(item => item.status === queryParams.status)
    }
    
    tableData.value = filteredData
    total.value = 100 // 模拟总数据量
    
    loading.value = false
  }, 500)
}

// 重置查询
const resetQuery = () => {
  queryParams.username = ''
  queryParams.status = ''
  queryParams.pageNum = 1
  getList()
}

// 处理分页
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 新增/编辑用户
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '添加用户'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  resetForm()
  dialogTitle.value = '编辑用户'
  dialogVisible.value = true
  
  // 填充表单数据
  Object.keys(formData).forEach(key => {
    if (row[key] !== undefined) {
      formData[key] = row[key]
    }
  })
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      
      // 模拟提交
      setTimeout(() => {
        ElMessage.success(formData.id ? '修改成功' : '添加成功')
        dialogVisible.value = false
        getList()
        loading.value = false
      }, 500)
    }
  })
}

// 重置表单
const resetForm = () => {
  formData.id = ''
  formData.username = ''
  formData.nickname = ''
  formData.email = ''
  formData.mobile = ''
  formData.sex = ''
  formData.status = '1'
  formData.roleIds = []
  formData.deptId = ''
  formData.remark = ''
  
  // 如果表单已经创建，则重置校验
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除用户"${row.username}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    
    // 模拟删除
    setTimeout(() => {
      ElMessage.success('删除成功')
      getList()
      loading.value = false
    }, 500)
  }).catch(() => {})
}

// 批量删除
const multipleSelection = ref([])
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的${multipleSelection.value.length}个用户吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    
    // 模拟删除
    setTimeout(() => {
      ElMessage.success('批量删除成功')
      getList()
      loading.value = false
    }, 500)
  }).catch(() => {})
}

// 改变状态
const handleStatusChange = (row) => {
  const statusText = row.status === '1' ? '启用' : '停用'
  
  ElMessageBox.confirm(`确定要${statusText}用户"${row.username}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    
    // 模拟API请求
    setTimeout(() => {
      ElMessage.success(`${statusText}成功`)
      row.status = row.status === '1' ? '0' : '1'
      loading.value = false
    }, 500)
  }).catch(() => {
    // 状态切换失败，还原状态
    row.status = row.status === '1' ? '0' : '1'
  })
}

// 角色名称
const getRoleNames = (roleIds) => {
  if (!roleIds || roleIds.length === 0) return '-'
  
  return roleIds.map(id => {
    const role = roleOptions.value.find(item => item.id === id)
    return role ? role.name : ''
  }).filter(name => name).join('，')
}

// 部门名称
const getDeptName = (deptId) => {
  if (!deptId) return '-'
  
  const dept = deptOptions.value.find(item => item.id === deptId)
  return dept ? dept.name : '-'
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="getList"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="getList">
            <el-icon><el-icon-search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><el-icon-refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表格工具栏 -->
    <el-card shadow="hover" class="table-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">用户列表</span>
          <div class="card-tools">
            <el-button type="primary" @click="handleAdd">
              <el-icon><el-icon-plus /></el-icon> 新增
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">
              <el-icon><el-icon-delete /></el-icon> 批量删除
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户编号" prop="id" width="80" align="center" />
        <el-table-column label="用户名" prop="username" align="center" />
        <el-table-column label="昵称" prop="nickname" align="center" />
        <el-table-column label="邮箱" prop="email" align="center" />
        <el-table-column label="手机号码" prop="mobile" align="center" />
        <el-table-column label="性别" align="center">
          <template #default="scope">
            <span v-if="scope.row.sex === '0'">未知</span>
            <span v-else-if="scope.row.sex === '1'">男</span>
            <span v-else-if="scope.row.sex === '2'">女</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="'1'"
              :inactive-value="'0'"
              @change="() => handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="所属角色" align="center">
          <template #default="scope">
            {{ getRoleNames(scope.row.roleIds) }}
          </template>
        </el-table-column>
        <el-table-column label="所属部门" align="center">
          <template #default="scope">
            {{ getDeptName(scope.row.deptId) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdTime" align="center" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button text type="primary" @click="handleEdit(scope.row)">
              <el-icon><el-icon-edit /></el-icon> 编辑
            </el-button>
            <el-button text type="danger" @click="handleDelete(scope.row)">
              <el-icon><el-icon-delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" append-to-body destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" :disabled="!!formData.id" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="formData.sex">
            <el-radio label="0">未知</el-radio>
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="formData.roleIds" multiple placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select v-model="formData.deptId" placeholder="请选择部门">
            <el-option
              v-for="item in deptOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.app-container {
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .card-title {
        font-weight: bold;
      }
      
      .card-tools {
        display: flex;
        gap: 10px;
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 